package com.wys.common.valid;

import lombok.val;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;
import java.util.Set;

/**
 * @Package com.wys.common.valid
 * @Author charlin
 * @Version: v1.0
 * @Date 2021-06-1821:38
 * @Copyright: 2021 www.wyscha.com Inc. All rights reserved.
 */
public class ListValueConstrainValidator implements ConstraintValidator<ListValue, Integer> {

    private Set<Integer> set = new HashSet<>();

    /**
     * 初始化集合
     * @param constraintAnnotation
     */
    @Override
    public void initialize(ListValue constraintAnnotation) {
        int[] vals = constraintAnnotation.vals();
        if(vals != null && vals.length > 0){
            for (int val : vals) {
                set.add(val);
            }
        }
    }

    /**
     * 检验value值是否在集合中
     *      @ListValue(vals = {0, 1}, groups = {AddGroup.class, UpdateStatusGroup.class})
     *     private Integer showStatus;
     * @param value
     * @param constraintValidatorContext
     * @return
     */
    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext constraintValidatorContext) {
        return set.contains(value);
    }


}
